package cn.demon.user.service.impl;

import cn.demon.basic.constant.VerifyConstants;
import cn.demon.basic.controller.VerifyCodeController;
import cn.demon.basic.exception.BusinessException;
import cn.demon.basic.util.MD5Utils;
import cn.demon.basic.util.StrUtils;
import cn.demon.org.domain.Employee;
import cn.demon.user.domain.Logininfo;
import cn.demon.user.domain.User;
import cn.demon.user.dto.UserDto;
import cn.demon.user.mapper.LogininfoMapper;
import cn.demon.user.mapper.UserMapper;
import cn.demon.user.service.IUserService;
import cn.demon.basic.service.impl.BaseServiceImpl;
import jdk.nashorn.internal.runtime.options.LoggingOption;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;




    @Override
    public void add(User user) {
        super.add(user);
    }

    @Override
    public void del(Long id) {
        // 获取登录信息
        Long logininfoId = userMapper.loadById(id).getLogininfoId();
        // 删除登录信息
        logininfoMapper.remove(logininfoId);
        // 删除user(用户)信息
        super.del(id);
    }


    @Override
    public void update(User user) {
        // 通过工具类获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码加密加盐
        String byMd5 = MD5Utils.encrypByMd5(user.getPassword() + salt);
        // 更新user密码
        user.setPassword(byMd5);
        // 更新盐值
        user.setSalt(salt);

        // 获取登录信息id
        Long logininfoId = userMapper.loadById(user.getId()).getLogininfoId();
        // 调用方法复制user信息
        Logininfo logininfo = user2Logininfo(user);
        // 设置登录信息id
        logininfo.setId(logininfoId);
        // 保存到数据库
        logininfoMapper.update(logininfo);

        // 修改用户信息
        super.update(user);
    }


    /**
     * 手机注册
     * @param userDto
     */
    @Override
    public void phoneRegister(UserDto userDto) {
        // 1.判断是否空值
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();

        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat) ||
                StringUtils.isEmpty(phone) ||StringUtils.isEmpty(phoneCode))
        {
           throw new BusinessException("数据不能为空！");
        }


        // 2.校验 - 密码一致校验 trim()-去空格
        if(!password.trim().equals(passwordRepeat.trim())){
            throw new BusinessException("两次密码不一致");
        }

        //3.校验 - 验证码是否过期 :  9527:441122222
        Object redisPhoneCode = redisTemplate.opsForValue().get(VerifyConstants.REGISTER_CODE_PREFIX + phone);
        if(redisPhoneCode == null){
            throw new BusinessException("手机验证码失效");
        }

        // 4.判断验证码是否正确
        if (!redisPhoneCode.toString().split(":")[0].equalsIgnoreCase(phoneCode)){
            throw new BusinessException("验证码输入错误！");
        }

        //5.添加 - t_logininfo信息
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        //6.添加 - t_user信息
        //设置登录信息id
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    /**
     * 邮箱注册
     * @param userDto
     */
    @Override
    public void emailRegister(UserDto userDto) {
        // 1.判断是否空值
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();
        String email = userDto.getEmail();

        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat) ||
                StringUtils.isEmpty(email))
        {
            throw new BusinessException("数据不能为空！");
        }


        // 2.校验 - 密码一致校验 trim()-去空格
        if(!password.trim().equals(passwordRepeat.trim())){
            throw new BusinessException("两次密码不一致");
        }
       // 3..校验 - 邮箱是否注册过
        //为什么要用User不用Logininfo：其实可以用Logininfo去查询，但是需要多传入一个type
        User user = userMapper.loadByEmail(email);
        if(user != null){
            throw new BusinessException("此邮箱已经注册，请直接登录，忘记密码请联系管理员!!!");
        }

        //4..添加 - t_logininfo信息
        User user1 = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user1);
        logininfoMapper.save(logininfo);

        //5..添加 - t_user信息
        //设置登录信息id
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);



    }

    /**
     * 创建copy信息方法
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        //设置为用户
        logininfo.setType(1);
        return logininfo;
    }

    /**
     * 创建添加user方法
     * @param userDto
     * @return
     */
    private User userDto2User(UserDto userDto) {
        // 数据字段根据需求对应
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());

        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5Pwd);
        return user;
    }
}